package com.xiaoger.jwt.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * jwtUtil
 *
 * @author xjx
 * @date 2022/5/14 10:40
 */
public class JwtUtil {
    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * 过期时间设置为10分钟
     */
    private static final long EXPIRE_TIME = 10 * 60 * 1000;

    /**
     * 创建token
     *
     * @param username 用户名
     * @param password 密码
     * @return token
     */
    public static String createToken(String username, String password) {
        long expiration = System.currentTimeMillis() + EXPIRE_TIME;
        Date expireDate = new Date(expiration);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(expireDate);
        logger.info("token的过期时间是：{}", format);
        //创建token
        String token = JWT.create()
                .withClaim("sys_username", username)
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(password));
        logger.info("创建的token为：{}", token);
        return token;
    }

    /**
     * 校验token是否正确
     *
     * @param token    token字符串
     * @param username 用户名
     * @param password 密码
     * @return 校验是否成功
     */
    public static Boolean verify(String token, String username, String password) throws Exception {
        Algorithm algorithm = Algorithm.HMAC256(password);
        JWTVerifier verifier = JWT.require(algorithm)
                .withClaim("sys_username", username)
                .build();
        verifier.verify(token);
        return true;
    }

    /**
     * 解析token 获取用户名
     *
     * @param token token
     * @return 用户名
     */
    public static String getUsername(String token) {
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim("sys_username").asString();
    }

    /**
     * 验证token是否失效
     *
     * @param token token
     * @return true:过期   false:没过期
     */
    public static boolean isExpired(String token) {
        try {
            final Date expiration = getExpiration(token);
            return expiration.before(new Date());
        } catch (JWTDecodeException JWT) {
            return true;
        }
    }

    /**
     * 获取jwt失效时间
     *
     * @param token token
     * @return 失效时间
     */
    public static Date getExpiration(String token) {
        return JWT.decode(token).getExpiresAt();
    }

}
